package com.example.mymenu.manager;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;

import com.example.mymenu.HttpbinService;
import com.example.mymenu.bean.MyAskBean;
import com.example.mymenu.bean.MyTakeBean;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetworkManager {

    private HttpbinService httpbinService;
    private Retrofit retrofit;
    private DataManager dataManager;
    private DbManager dbManager;
    private Context context;

    public NetworkManager(Context context){
        retrofit = new Retrofit.Builder().baseUrl("http://172.20.4.149:6611/").addConverterFactory(GsonConverterFactory.create()).build();
        httpbinService = retrofit.create(HttpbinService.class);
        dataManager = new DataManager();
        //dbManager = new DbManager(context);
        this.context = context;
    }

    //关闭
    public void close(){
        dbManager.close();
    }

    //POST请求获取菜谱数据
    public MyTakeBean postMenu(String findMessage){
        MyAskBean myAskBean = dataManager.updateAskBean(findMessage);
        final MyTakeBean[] myTakeBean = {null};
        Call<MyTakeBean> call = httpbinService.post(myAskBean);
        call.enqueue(new Callback<MyTakeBean>() {
            @Override
            public void onResponse(Call<MyTakeBean> call, Response<MyTakeBean> response) {
                //服务器返回正确信息
                if (response.raw().code() == 200){
                    if(response.body().getPayload().getListItems() != null){
                        dbManager = new DbManager(context);
                        if(response.body().getPayload().getListItems().size() != 0) {
                            MyTakeBean.PayloadBean.ListItemsBean msgBean = response.body().getPayload().getListItems().get(0);
                            Cursor cursor = dbManager.query("menu", null, new String("menu_id=?"), new String[]{msgBean.getId()}, null, null, null);
                            if (cursor.getCount() == 0) {
                                ContentValues contentValues = new ContentValues();
                                contentValues.put("menu_id", Integer.parseInt(msgBean.getId()));
                                contentValues.put("name", msgBean.getName());
                                contentValues.put("time", msgBean.getCookingtime());
                                contentValues.put("content", msgBean.getContent());
                                contentValues.put("marterial", msgBean.getMaterial());
                                contentValues.put("pcontent", msgBean.getPcontent());
                                contentValues.put("function", response.body().getQuery());
                                contentValues.put("pic",dataManager.getStepImageMessage(msgBean));
                                dbManager.insert("menu", null, contentValues);
                                //发送广播
                                Integer columnsNumber = dbManager.queryColumnsNumber("menu");
                                Intent intentBroadcast = new Intent();
                                intentBroadcast.putExtra("columnsNumber", columnsNumber.toString());
                                intentBroadcast.setAction("com.my.app");
                                context.sendBroadcast(intentBroadcast);
                                myTakeBean[0] = response.body();
                                Log.d("Service", "InsertSuccess");
                            }
                            dbManager.close();
                            Log.d("Service", "success");
                        }
                    }else{
                        Log.d("Service","resultFailed");
                    }


                }else{
                    Log.d("Service","failed");
                }
            }

            @Override
            public void onFailure(Call<MyTakeBean> call, Throwable t) {
                Log.d("msg", "failed: " + t.toString());
            }
        });
        return myTakeBean[0];
    }

    //网络请求加载图片
    /*public InputStream getImageViewInputStream(String internetPath) throws IOException{
        InputStream inputStream = null;
        URL url = new URL(internetPath);
        if (url != null) {
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);
            Integer responseCode = httpURLConnection.getResponseCode();
            if(responseCode == 200){
                inputStream = httpURLConnection.getInputStream();
            }
        }
        return inputStream;
    }*/
}
